package com.example.other.utils;


import com.example.other.common.Constant;
import com.example.other.entity.ClassInfo;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang.StringUtils;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @description：TODO
 * @author：yufan.wang
 * @create：2024/3/15 17:34
 */
@Slf4j
@Component
public class VelocityUtils {

    private static final String PROJECT_PATH = "main/java";

    public static void main(String[] args) {
        // 创建Scanner对象，用于接收用户输入
        Scanner scanner = new Scanner(System.in);

        // 提示用户输入三个整数
        System.out.println("请输入第一个整数：");
        int num1 = scanner.nextInt();

        System.out.println("请输入第二个整数：");
        int num2 = scanner.nextInt();

        System.out.println("请输入第三个整数：");
        int num3 = scanner.nextInt();

        // 关闭scanner，不再需要输入
        scanner.close();

        // 计算三个整数的和
        int sum = num1 + num2 + num3;

        // 计算平均值
        double average = (double) sum / 3;

        // 输出结果
        System.out.println("三个整数的和为：" + sum);
        System.out.println("三个整数的平均值为：" + average);
    }


    @Autowired
    private ResourceLoader resourceLoader;

    /**
     * 初始化vm方法
     */
    public void initVelocity() {
        Properties p = new Properties();
        try {
            // 加载classpath目录下的vm文件
            p.setProperty("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
            // 定义字符集
            p.setProperty(Velocity.ENCODING_DEFAULT,  Constant.UTF8);
            p.setProperty(Velocity.OUTPUT_ENCODING, Constant.UTF8);
            // 初始化Velocity引擎，指定配置Properties
            Velocity.init(p);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取代码生成地址
     *
     * @param classInfo 类信息
     * @param template  模板文件路径
     * @return 生成地址
     */
    public String getGenPath(ClassInfo classInfo, String template) {
        String genPath = classInfo.getGenPath();
        String path = "";
        if (StringUtils.equals(genPath, "/")) {
            path = System.getProperty("user.dir") + File.separator + "src" + File.separator + getFileName(template, classInfo);
            log.info("===>文件生成路径 {}", path);
            return path;
        }
        path = genPath + "/" + VelocityUtils.getFileName(template, classInfo);
        log.info("===>文件生成路径 {}", path);
        return path;
    }

    private static String getFileName(String template, ClassInfo classInfo) {
        String className = classInfo.getClassName();
        //首字符转大写
        className = className.substring(0, 1).toUpperCase() + className.substring(1);
        String javaPath = "gen/" + className;
        if (template.contains("reqDto.java.vm")) {
            return String.format("%s/request/%sReqDto.java", javaPath, className);
        }
        return "";
    }


    /***
     * 设置模板变量信息
     * @return VelocityContext
     */
    public VelocityContext prepareContext(Object clas) {

        VelocityContext velocityContext = new VelocityContext();

        Field[] fields = clas.getClass().getDeclaredFields();
        Field[] declaredFields = clas.getClass().getSuperclass().getDeclaredFields();

        // 创建一个新数组，长度是两个数组长度之和
        Field[] mergedArray = new Field[fields.length + declaredFields.length];
        System.arraycopy(fields, 0, mergedArray, 0, fields.length);
        System.arraycopy(declaredFields, 0, mergedArray, fields.length, declaredFields.length);

        for (Field field : mergedArray) {
            field.setAccessible(true); // 使私有字段也可以访问
            try {
                Object value = field.get(clas);
                System.out.println("velocityContext.put ===> "+field.getName() + " = " + value);
                velocityContext.put(field.getName(), value);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }


        return velocityContext;
    }


    /**
     * 获取模板信息
     *
     * @return 模板列表
     */
    public List<String> getTemplateList() {

        Resource resource = resourceLoader.getResource("classpath:templates/java/");
        if (resource.exists()) {
            try {
                return Files.walk(Paths.get(resource.getURI())).filter(Files::isRegularFile).map(path -> "/templates/java/" + path.getFileName().toString()).collect(Collectors.toList());
            } catch (IOException e) {
                throw new RuntimeException();
            }
        } else {
            throw new RuntimeException("资源文件目录不存在");
        }
    }


}
